import React, { Component } from 'react';

import './App.css';
function convertClass(obj){
  var classStr =''
  for(var key in obj){
    if(obj[key]){
      classStr += key+'';
    }
  }
  return classStr;
}
class App extends Component {
  constructor(){
    super();
    this.state = {
      newContent:'',
      todos:[
        { id:1,isCompleted:true,content:'吃饭'},
        { id:2,isCompleted:false,content:'睡觉'},
        { id:3,isCompleted:true,content:'打豆豆'}
      ],
      nowId:-1,
      leftNum:0,
      checkAll:false,
      showClear:false,
      filter:'#/',
    }
  }
  renderList(){
    let { todos,filter } = this.state;
    return this.state.todos.map((item)=>{
      if (filter === '#/active' && item.isCompleted) return null;
      if (filter === '#/completed' && !item.isCompleted) return null;
      return(
          <li className={convertClass({completed:item.isCompleted,editing:this.state.nowId == item.id})} key={item.id}>
            <div className="view">
              <input className="toggle" type="checkbox" checked={item.isCompleted} onChange={e=>this.checkHandler(e,item)}/>
              <label onDoubleClick={e=>this.beginEdit(item)}>{item.content}</label>
              <button className="destroy" onClick={ e=> this.delTodo(item)}></button>
            </div>
            <form onSubmit={e=>this.endEdit(e)}>
              <input className="edit" value={item.content} ref={'edit_'+item.id} onBlur={e=>this.endEdit(e)} onChange={e=>this.saveEdit(e,item)}/>
            </form>
          </li>
      )
    });
  }
  //绑定数据
  contentHandler(e){
    this.setState({
      newContent:e.target.value,
    })
  }
  addTodo(e){

    //阻止默认事件
    e.preventDefault();
    //验证不能为空
    if(this.state.newContent.toString().trim() === '') return;
    let maxId = 0;
    this.state.todos.forEach((item)=>{
      if(item.id>maxId){
        maxId = item.id;
      }
    });
    maxId++;
    this.state.todos.push({
      id:maxId,
      isCompleted:false,
      content:this.state.newContent,
    });
    this.setState({
      newContent:''
    });
    this.getCountLeft();
  }
  //删除
  delTodo(item){
    let { todos } = this.state;
    // 找索引 find函数找元素,findIndex找索引
    //console.log(item.id);
    let index = todos.findIndex(function (t) {
      if(t.id === item.id) return true;
    } );
    console.log(index);
    // 删除元素
    todos.splice(index,1);
    this.setState({});
    this.getCountLeft();
  }
  //checkbox的绑定
  checkHandler(e,item){
    item.isCompleted = e.target.checked;
    //this.setState({});
    this.getCountLeft();
  }
  //开始编辑
  beginEdit(item){
    this.setState({
      nowId:item.id,
    },()=>{
      this.refs['edit_'+item.id].focus();
    })
  }
  //保存修改
  saveEdit(e,item){
    item.content = e.target.value
    this.setState({})
  }
  //结束修改
  endEdit(e){
    //阻止默认行为
    e.preventDefault();
    this.setState({
      nowId:-1,
    })
  }
  //得到剩余数
  getCountLeft(){
    var num = 0;
    var toggleAllChecked = true;
    this.state.showClear = false;
    this.state.todos.forEach((item)=>{
      //这个逻辑较难理解
      if(!item.isCompleted){
        num++;
        toggleAllChecked = false
      }else{
        this.state.showClear = true;
      }
    });
    this.setState({
      leftNum:num,
      checkAll:toggleAllChecked,
    })
  }
  componentDidMount() {
    this.getCountLeft();
    //console.log(this.state.leftNum);
    this.renderByHash();
  }
  //全选全不选
  changeToggleAll(e){
    this.state.todos.forEach((item)=>{
      item.isCompleted = e.target.checked;
    });
    this.setState({
      checkAll:e.target.checked,
    })
  }
  //清除完成的todo
  clearCompleted(){
    let {todos} = this.state;
    for(var i = todos.length - 1;i>=0;i--){
      if(todos[i].isCompleted){
        todos.splice(i,1)
      }
    }
    this.setState({});
  }
  //获取fliter
  filterRender(e){
    this.setState({
      filter:e.target.hash,
    })
  }
  renderByHash(){
    this.state.filter = window.location.hash;
    //console.log(window.location.hash);
    window.addEventListener('hashchange',()=>{
      this.state.filter = window.location.hash;
      this.setState({});
    })
  }


  render() {
    return (
     <React.Fragment>
       <section className="todoapp">
         <header className="header">
           <h1>todos</h1>
           <form onSubmit={e => this.addTodo(e)}>
              <input className="new-todo" placeholder="What needs to be done?" autoFocus="" onChange={e =>{this.contentHandler(e)}} onBlur={e => this.addTodo(e)}/>
           </form>
         </header>
         {/* This section should be hidden by default and shown when there are todos */}
         <section className="main">
           <input id="toggle-all" className="toggle-all" type="checkbox" checked={this.state.checkAll} onChange={e =>this.changeToggleAll(e)}/>
             <label htmlFor="toggle-all">Mark all as complete</label>
             <ul className="todo-list">
               {/* These are here just to show the structure of the list items */}
               {/* List items should get the class `editing` when editing and `completed` when marked as completed */}
               {this.renderList()}

             </ul>
         </section>

         <footer className="footer">
           <span className="todo-count"><strong>{this.state.leftNum}</strong> item left</span>
          
           <ul className="filters">
             <li>
               <a className="selected" href="#/" onClick={e=>this.filterRender(e)}>All</a>
             </li>
             <li>
               <a href="#/active" onClick={e=>this.filterRender(e)}>Active</a>
             </li>
             <li>
               <a href="#/completed" onClick={e=>this.filterRender(e)}>Completed</a>
             </li>
           </ul>
           {/*Hidden if no completed items are left ↓ */}
           {this.state.showClear&&<button className="clear-completed" onClick={ e=> this.clearCompleted()}>Clear completed</button>}
         </footer>
       </section>
     </React.Fragment>
    );
  }
}

export default App;
